//
//  BVPersonInfomatonViewController.m
//  BuyVegetables
//
//  Created by 叶思超 on 15/10/19.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//

#import "BVPersonInfomatonViewController.h"
#import "BVConst.h"
#import "UIView+Extension.h"
#import "AppDelegate.h"
#import "BVLoginViewController.h"
#import "HttpTool.h"


@interface BVPersonInfomatonViewController ()
/**
 *  姓名
 */
@property (nonatomic, strong) UITextField *nameF;
/**
 *  昵称
 */
@property (nonatomic, strong) UITextField *nickF;
/**
 *  公司名称
 */
@property (nonatomic, strong) UITextField *companyF;
@end

@implementation BVPersonInfomatonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 导航栏基本设置
    [self setupNav];

    // 获取用户个人信息
//    [self setupPersonalInfo];
    
    // 设置UI
    [self setupUI];
}

#pragma mark -- 获取用户个人信息
- (void)setupPersonalInfo {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/getUserInfoById", Path];
    
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [defaults dictionaryForKey:@"userInfo"];
    NSString *user_id = dict[@"id"];
    if (user_id != nil) {
        params[@"user_id"] = user_id;
        
        [HttpTool get:url params:params success:^(id responseObj) {
            if ([responseObj[@"code"] isEqualToString:@"1"]) {
                BVLog(@"获取个人信息成功-----%@", responseObj);
            } else {
                BVLog(@"获取个人信息失败-----%@", responseObj);
            }
        } failure:^(NSError *error) {
            BVLog(@"请求失败-----%@", error);
        }];
    } else  {
        
    }
}

#pragma mark -- 设置UI
- (void)setupUI {
    // 姓名
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.frame = CGRectMake(10, 84, 80, 40);
    nameLabel.text = @" 姓       名:";
    nameLabel.textColor = BVBaseTextBlackColor;
    nameLabel.backgroundColor = [UIColor whiteColor];
    nameLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:nameLabel];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userinfo = [defaults dictionaryForKey:@"USERINFO"];
    
    // 获取名称
    self.nameF = [[UITextField alloc] init];
    self.nameF.frame = CGRectMake(CGRectGetMaxX(nameLabel.frame), nameLabel.y, BVScreenW - CGRectGetMaxX(nameLabel.frame) - 10, 40);
    self.nameF.textColor = BVBaseTextBlackColor;
    self.nameF.backgroundColor = [UIColor whiteColor];
    self.nameF.font = [UIFont systemFontOfSize:15];
    self.nameF.text = userinfo[@"username"];
    [self.view addSubview:self.nameF];
    
    // 分割线一
    UIView *oneSeperatorLine = [[UIView alloc] init];
    oneSeperatorLine.frame = CGRectMake(10, CGRectGetMaxY(nameLabel.frame), BVScreenW - 2 * 10, 0.7);
    oneSeperatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:oneSeperatorLine];
    
    // 昵称
    UILabel *nickLabel = [[UILabel alloc] init];
    nickLabel.frame = CGRectMake(10, CGRectGetMaxY(oneSeperatorLine.frame), 80, 40);
    nickLabel.text = @" 昵       称:";
    nickLabel.textColor = BVBaseTextBlackColor;
    nickLabel.backgroundColor = [UIColor whiteColor];
    nickLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:nickLabel];
    
    // 获取昵称
    self.nickF = [[UITextField alloc] init];
    self.nickF.frame = CGRectMake(CGRectGetMaxX(nickLabel.frame), nickLabel.y, BVScreenW - CGRectGetMaxX(nickLabel.frame) - 10, 40);
    self.nickF.textColor = BVBaseTextBlackColor;
    self.nickF.backgroundColor = [UIColor whiteColor];
    self.nickF.font = [UIFont systemFontOfSize:15];
    self.nickF.text = userinfo[@"nickname"];
    [self.view addSubview:self.nickF];
    

    // 分割线二
    UIView *twoSeperatorLine = [[UIView alloc] init];
    twoSeperatorLine.frame = CGRectMake(10, CGRectGetMaxY(nickLabel.frame), BVScreenW - 2 * 10, 0.5);
    twoSeperatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:twoSeperatorLine];
    
    // 公司名称
    UILabel *companyLabel = [[UILabel alloc] init];
    companyLabel.frame = CGRectMake(10, CGRectGetMaxY(twoSeperatorLine.frame), 80, 40);
    companyLabel.text = @" 公司名称:";
    companyLabel.textColor = BVBaseTextBlackColor;
    companyLabel.backgroundColor = [UIColor whiteColor];
    companyLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:companyLabel];
    
    // 获取昵称
    self.companyF = [[UITextField alloc] init];
    self.companyF.frame = CGRectMake(CGRectGetMaxX(companyLabel.frame), companyLabel.y, BVScreenW - CGRectGetMaxX(companyLabel.frame) - 10, 40);
    self.companyF.textColor = BVBaseTextBlackColor;
    self.companyF.backgroundColor = [UIColor whiteColor];
    self.companyF.font = [UIFont systemFontOfSize:15];
    self.companyF.text = userinfo[@"companyName"];
    [self.view addSubview:self.companyF];

    // 分割线三
    UIView *threeSeperatorLine = [[UIView alloc] init];
    threeSeperatorLine.frame = CGRectMake(10, CGRectGetMaxY(companyLabel.frame), BVScreenW - 2 * 10, 0.5);
    threeSeperatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:threeSeperatorLine];
    
    // 退出登录
    UIButton *quitButton = [[UIButton alloc] init];
    quitButton.frame = CGRectMake(10, CGRectGetMaxY(threeSeperatorLine.frame) + 80, BVScreenW - 2 * 10, 40);
    quitButton.backgroundColor = BVBaseOrangeColor;
    quitButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [quitButton setTitle:@"退       出" forState:UIControlStateNormal];
    [quitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [quitButton addTarget:self action:@selector(quitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    quitButton.layer.borderWidth = 1;
    quitButton.layer.borderColor = [UIColor whiteColor].CGColor;
    quitButton.layer.masksToBounds = YES;
    quitButton.layer.cornerRadius = 4;
    [self.view addSubview:quitButton];
}

#pragma mark -- 退出
- (void)quitButtonClick {
    // 清缓存
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:nil forKey:@"USERINFO"];

    [[NSNotificationCenter defaultCenter] postNotificationName:LogOutSuccessNotification object:nil userInfo:nil];
    ROOTNAVPOP
    
}

#pragma mark -- 导航栏基本设置
- (void)setupNav {
    self.navigationController.navigationBar.barTintColor = BVBaseOrangeColor;
    
    self.title = @"个人信息";
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(saveButtonClick)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];
}

#pragma mark -- 保存信息修改
- (void)saveButtonClick {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/doSaveUserInfoById", Path];
    
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary * userInfo = [defaults objectForKey:@"USERINFO"];
    NSString * user_id = userInfo[@"id"];
    
    if (user_id != nil) {
        params[@"user_id"] = user_id;
        params[@"username"] = self.nameF.text;
        params[@"nickname"] = self.nickF.text;
        params[@"companyName"] = self.companyF.text;
        
        [HttpTool get:url params:params success:^(id responseObj) {
            if ([responseObj[@"code"] isEqualToString:@"1"]) {
                BVLog(@"修改个人信息成功-----%@", responseObj);
                [self updateUserInfo];
            } else {
                BVLog(@"修改个人信息失败-----%@", responseObj);
            }
        } failure:^(NSError *error) {
            BVLog(@"请求失败-----%@", error);
        }];
    } else  {
        
    }
}
#pragma mark  重新请求用户信息
- (void)updateUserInfo{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * userinfo = [[defaults objectForKey:@"USERINFO"] mutableCopy];
    NSString * userid = userinfo[@"id"];
    [manager POST:@"http://app.jingcaibuy.com/VegetableUserAPI/getUserInfoById" parameters:@{@"user_id":userid} success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary * baseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSDictionary * dataDict = baseDict[@"data"];
        
        
        NSArray * allKey = dataDict.allKeys;
        for (NSString * key in allKey) {
            userinfo[key] = [dataDict objectForKey:key];
        }
        
        [defaults setObject:userinfo forKey:@"USERINFO"];
        [defaults synchronize];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:SaveUserInfoSuccess object:nil userInfo:nil];
        ROOTNAVPOP

    } failure:^(NSURLSessionDataTask *task, NSError *error) {

        
    }];
}
#pragma mark -- 返回
- (void)backClick {
    ROOTNAVPOP
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
@end
